package com.demo.sender.email.config;

import com.mailgun.api.v3.MailgunMessagesApi;
import com.mailgun.client.MailgunClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @author wangfengchen
 */
@Data
@Configuration
public class EmailClientConfig {


  @Value("${email.mailGun.apiKey:not_set}")
  private String apiKey;
  /**
   * 发送邮件服务器
   */
  @Value("${email.javaMail.host:not_set}")
  private String host;
  /**
   * 发送邮件的邮箱地址
   */
  @Value("${email.javaMail.username:not_set}")
  private String username;
  /**
   * 企业邮箱是密码，qq和网易是授权码
   */
  @Value("${email.javaMail.password:not_set}")
  private String password;


  /**
   * 获取同步客户端
   *
   * @return
   */
  @Bean
  public MailgunMessagesApi mailgunMessagesApi() {
    return MailgunClient.config(apiKey).createApi(MailgunMessagesApi.class);
  }

  /**
   * 获取异步客户端
   *
   * @return
   */
  @Bean
  public MailgunMessagesApi mailgunAsyncMessagesApi() {
    return MailgunClient.config(apiKey).createAsyncApi(MailgunMessagesApi.class);
  }

  @Bean
  @Primary
  @ConditionalOnMissingBean
  public JavaMailSender buildEmailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost(host);
    mailSender.setUsername(username);
    mailSender.setPassword(password);
    mailSender.setDefaultEncoding(StandardCharsets.UTF_8.toString());
    // 加认证机制
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.ssl.enable", "true");
    // 防止文件名过长错误ATTxx.bin进行全局定义
    properties.setProperty("mail.mime.splitlongparameters", "false");
    properties.setProperty("mail.smtp.socketFactory.port", "465");
    properties.setProperty("mail.smtp.socketFactory.fallback", "false");
    properties.setProperty("mail.smtp.socketFactory.class",
        "javax.net.ssl.SSLSocketFactory");
    mailSender.setJavaMailProperties(properties);
    return mailSender;
  }


}
